<template>
  <div class="container">
    <div class="head">
      <div class="img">
        <img src="../../assets/NJUST.jpeg" />
      </div>
      <div class="person">
        <img src="../../assets/用户名.png" />
  <li class="li1"><router-link to="/person"><span>个人主页</span></router-link></li>
  </div>
  <div class="list">
    <img src="../../assets/购物车.png" />
  <li class="li1"><router-link to="/sample"><span>我的清单</span></router-link></li>
  </div>
  </div>

  <div class="crumbs">
    <nav>
      <router-link to="/home1"><span>首页</span><span>/</span></router-link>
               <router-link to="/home1"><span>{{ staName}}</span><span>/</span></router-link>
               <router-link :to="{
                 name: 'Home2', 
                 params: {
          param:this.staId,
          param1: this.staName,
               }
              }"><span>{{ pjName}}</span><span>/</span></router-link>
               <router-link :to="{
                 name: 'module', 
                 params: {
          staName: this.staName,
          pjName: this.pjName,
          pjId: this.pjId,
          staId:this.staId
               }
              }"><span>人员-培训</span></router-link>
      <!-- <router-link to="/home1"><span>首页 </span></router-link><span>/</span>
      <router-link to="/home2"><span>xxxx标准 </span></router-link><span>/</span>
      <router-link to="module"><span>xxxx项目</span></router-link><span>/</span>
      <router-link to="#"><span>人员-培训</span></router-link> -->
    </nav>
  </div>

  <div class="main-content">
    <div class="nav">
      <a href="#" class="active">培训</a> |
      <el-button type="text" @click="checkProgress" class="exam-button">考核</el-button>
    </div>
    <div class="progress-container">
      <label>学习进度：</label>
      <progress :value="study.sStatus" max="100" class="progress-bar"></progress>
      <span class="progress-value">{{ study.sStatus }}%</span>
    </div>

    <div class="tasks">
      <div class="task" v-for="(task, index) in tasks" :key="task.id">
        <div class="task-label">
          <h2 class="task-title">任务 {{ index + 1 }}</h2>
        </div>

        <div class="task-content">
          <div class="task-video">
            <video 
              ref="videoPlayer"
              controls 
              class="video-player" 
              @ended="videoEnded(task.id)"
              @error="handleVideoError"
              @play="handleVideoPlay($event, index)"
              :key="task.url"
            >
              <source :src="task.url" type="video/mp4">
              <div class="video-fallback">您的浏览器不支持视频播放，请更换浏览器或更新版本。</div>
            </video>
          </div>
          <div class="task-status">
            <span :class="{'completed': task.completed, 'not-completed': !task.completed}">
              <span class="status-dot"></span>
              {{ task.completed ? '已完成' : '未完成' }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="chatbot">
    <img src="../../assets/客服.png" />
    <span class="chatbot-text">未找到所需内容？</span>
    <a href="#" class="chatbot-link" @click="toggleChatbot">点我留言</a>
  </div>

  <!-- 遮罩层 -->
  <div v-if="isChatbotVisible" class="chatbot-mask"></div>

  <!-- 弹出框 -->
  <div v-if="isChatbotVisible" class="chatbot-popup">
    <h2>留言板</h2>
    <textarea v-model="message" rows="4" cols="50" placeholder="请输入您的留言..."></textarea>
    <div class="popup-actions">
      <el-button type="primary" @click="submitMessage">提交留言</el-button>
      <el-button @click="toggleChatbot">关闭</el-button>
    </div>
  </div>

  </div>
</template>

<script>
export default {
  name: 'TrainingStatus',
  data() {
    return {
      study:{

      },
      staName:'',
      pjName:'',
      pjId:'',
      staId:'',
      isChatbotVisible: false, // 控制弹出框显示
      message: '', // 绑定留言内容
      tasks: [
        // { videoLink: '#video1', completed: true },
        // { videoLink: '#video2', completed: true },
        // { videoLink: '#video3', completed: false }
      ]
    };
  },
  created: function() {
    
  this.pjId = this.$route.params.pjId;
  this.pjName = this.$route.params.pjName;
  this.staName = this.$route.params.staName;
  this.staId = this.$route.params.staId;
  console.log("这个是training的值："+this.pjId);
  this.getStudy();
},
  computed: {
    progressPercentage() {
      return this.tasks.filter(task => task.completed).length / this.tasks.length * 100;
    }
  },
  watch: {
    'study.sStatus': {
      immediate: true, // 立即执行
      handler(newValue) {
        if (newValue === 100) {
          this.$http.post('http://localhost:8081/training/addTextToCertificate1', {
            sId: this.study.sId
          }).then(response => {
            this.$message({
              type: 'success',
              message: '证书已生成！'
            });
          }).catch(error => {
            console.error('生成证书失败:', error);
            this.$message.error('证书生成失败，请重试');
          });
        }
      }
    }
  },
  methods: {
    getStudy(){
      this.$http.get(`/findStudyByPjId/${this.pjId}`).then((response) => {
      this.study=response.data;
      this.convertMapToArray(response.data.videoWatchStatus); 
  });
    },
    convertMapToArray(videoWatchStatus) {
    const tasksPromises = Object.keys(videoWatchStatus).map(key => {
      const videoId = parseInt(key);
      return this.getVideoUrl(videoId).then(url => ({
        id: videoId,
        url: url,
        completed: videoWatchStatus[key]
      }));
    });
    // 等待所有 Promise 解析完成
    Promise.all(tasksPromises).then(tasks => {
      this.tasks = tasks; // 时 tasks 将包含解析后的数据
      console.log(this.tasks);
    });
    
  },
  getVideoUrl(videoId) {
    return this.$http.get(`/getVideoUrl/${videoId}`).then(response => {
      return response.data.url;
    });
  },
    
    getVideoUrl(pgId) {
      // 根据视频 ID 从后端获取视频 URL
      return this.$http.get(`/getVideoUrl/${pgId}`).then(response => {
        return response.data;
      });
    },
    checkProgress() {
      if (this.study.sStatus < 90) {
        this.$alert('您的学习进度未达到要求!', '提示', {
          confirmButtonText: '继续学习',
          callback: action => {
            this.$message({
              type: 'info',
              message: `您的学习进度未达到要求!`
            });
          }
        });
      } else {
        this.$router.push({ name: 'Assessment' ,params:{staId:this.staId,staName:this.staName,pjId:this.pjId,sId:this.study.sId}});
      }
    },
     toggleChatbot() {
      this.isChatbotVisible = !this.isChatbotVisible; // 切换弹出框显示状态
    },
    submitMessage() {
      // 提交留言的逻辑
      console.log('留言内容:', this.message);
      // 可以在这里添加代码将留言发送到服务器
      this.$http.put(`/insertFeedback/${this.message}`).then((response)=>{
          
      }),
      this.isChatbotVisible = false; // 提交后隐藏弹出框
      this.message = ''; // 清空留言内容

      // 添加弹窗提示留言成功的逻辑
      this.$alert('留言成功！', '成功', {
        confirmButtonText: '确定',
        type: 'success'
      });
    },
    videoEnded(taskId) {
      this.$http.get("/downloadVideo", { 
        params: { 
          pgId: taskId, 
          pjId: this.pjId
        }
      }).then((response) => {
        this.getStudy();
        this.$message({
          type: 'success',
          message: '视频学习完成！',
          duration: 2000
        });
      }).catch(error => {
        console.error('更新学习状态失败:', error);
        this.$message.error('更新学习状态失败，请重试');
      });
    },
    handleVideoError(e) {
      console.error('视频加载失败:', e);
      this.$message({
        type: 'error',
        message: '视频加载失败，请稍后重试',
        duration: 3000
      });
    },
    handleVideoPlay(event, currentIndex) {
      // 暂停其他所有视频
      this.$refs.videoPlayer.forEach((video, index) => {
        if (index !== currentIndex) {
          video.pause();
        }
      });
    },
  }
}
</script>

<style scoped>
  /* 样式定义 */
  .container {
    width: 100%;
    margin: 0 auto;
    font-family: Arial, sans-serif;
  }

  .head {
    width: 100%;
    background-color: #abe0f3;
    height: 6vh;
  }

    .head .img {
      height: 100%;
      float: left;
    }

      .head .img img {
        height: 100%;
      }

    .head .list {
      float: right;
      height: 45%;
    }

      .head .list img {
        margin-top: 15px;
        margin-right: 7px;
        height: 100%;
        float: left;
      }

      .head .list li {
        margin-top: 20px;
        margin-right: 40px;
        display: block;
        float: left;
        font-size: 18px;
      }

    .head .person {
      float: right;
      height: 42%;
    }

      .head .person img {
        margin-top: 15px;
        margin-right: 7px;
        height: 100%;
        float: left;
      }

      .head .person li {
        margin-top: 20px;
        margin-right: 70px;
        display: block;
        float: left;
        font-size: 18px;
      }


  .nav a {
    margin-left: 10px;
    text-decoration: none;
    color: #000;
  }

    .nav a.active {
      background-color: #555;
      color: #fff;
      padding: 5px 10px;
      border-radius: 5px;
    }

  .crumbs {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    background-color: #f0f0f0;
  }

  .main-content {
    padding: 20px;
    /*text-align: center;*/ /* 使内容居中 */
  }

  h1{
    float: left;
  }

  .nav{
    float: right;
  }

    .nav a {
      margin-left: 10px;
      text-decoration: none;
      color: #000;
    }

      .nav a.active {
        background-color: #555;
        color: #fff;
        padding: 5px 10px;
        border-radius: 5px;
      }

  .exam-button {
    color: #000; /* 设置按钮文本颜色为黑色 */
    background-color: transparent; /* 确保按钮没有背景色 */
    border: none; /* 移除边框 */
    cursor: pointer; /* 鼠标悬停时显示为手型 */
  }

    .exam-button:hover {
      color: #409EFF; /* 鼠标悬停时的颜色 */
    }

  .progress-container {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 75%;
    max-width: 900px;
    margin: 24px auto;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    text-align: center;
  }

  .progress-bar {
    width: 50%;
    height: 12px;
    margin: 0 12px;
    border-radius: 6px;
    background: #f0f2f5;
  }

    .progress-bar::-webkit-progress-value {
      background-color: #4caf50; /* Green */
    }

  .progress-value {
    margin-left: 10px;
  }

  .tasks {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 75%;
    margin: 0 auto;
  }

  .task {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    padding: 12px 20px;
    margin-bottom: 16px;
    width: 100%;
    max-width: 900px;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
  }

  .task:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  .task-label {
    width: 100%;
    text-align: left; /* 任务编号左对齐 */
  }

  .task-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    gap: 16px;
  }

  .task-video {
    width: 35%;
  }

  .task-status {
    flex: 1;
    display: flex;
    justify-content: center;
    margin-left: 12px;
    padding: 6px 12px;
    border-radius: 4px;
    background: #f8f9fa;
  }

  .status-dot {
    content: '';
    display: inline-block;
    width: 10px; /* 小圆点的宽度 */
    height: 10px; /* 小圆点的高度 */
    margin-right: 5px; /* 小圆点与文字之间的间距 */
    border-radius: 50%; /* 使元素变成圆形 */
  }

  .completed .status-dot {
    background-color: green; /* 已完成状态的小圆点颜色 */
  }

  .not-completed .status-dot {
    background-color: red; /* 未完成状态的小圆点颜色 */
  }

  .completed {
    color: green;
  }

  .not-completed {
    color: red;
  }

  .chatbot {
    position: fixed;
    bottom: 20px;
    left: 20px;
    background-color: #f9f9f9;
    padding: 10px;
    border-radius: 5px;
    display: flex;
    align-items: center; /* 垂直居中对齐 */
  }

  .chatbot img{
    width: 70px;
    
  }

  .chatbot-text {
    margin-right: 10px; /* 与链接间距 */
  }

  .chatbot-link {
    color: black; /* 设置链接颜色为黑色 */
    text-decoration: underline; /* 添加下划线 */
    font-size: 16px; /* 设置字体大小 */
    transition: color 0.3s; /* 平滑色变化 */
  }

    .chatbot-link:hover,
    .chatbot-link:focus,
    .chatbot-link:active {
      color: black; /* 悬停、聚焦、点击时颜色不变 */
      text-decoration: underline; /* 保持下划线 */
    }

  .chatbot-popup {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    padding: 20px;
    border-radius: 5px;
    z-index: 1000; /* 确保弹出框在最上层 */
  }

  .chatbot-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5); /* 灰色半透明遮罩 */
    z-index: 999; /* 遮罩层在弹出框下一层 */
  }

  .popup-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
  }

  .chatbot-popup h2 {
    margin-top: 0; /* 移除标题的上边距 */
  }

  .chatbot-popup textarea {
    width: 100%;
    margin-bottom: 10px;
  }

  .aaa{
    width:500px;
  }

  .task-title {
    color: #303133;
    font-size: 16px;
    margin: 0 0 12px 0;
    font-weight: 600;
  }

  .video-player {
    width: 100%;
    max-width: 300px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .task-status {
    margin-left: 16px;
    padding: 8px 16px;
    border-radius: 4px;
    background: #f8f9fa;
  }

  .completed {
    color: #67c23a;
    font-weight: 500;
  }

  .not-completed {
    color: #f56c6c;
    font-weight: 500;
  }

  .status-dot {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 8px;
  }

  .completed .status-dot {
    background-color: #67c23a;
  }

  .not-completed .status-dot {
    background-color: #f56c6c;
  }

  .progress-container {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin: 24px auto;
    width: 80%;
    max-width: 1200px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .progress-bar {
    height: 12px;
    border-radius: 6px;
    background: #f0f2f5;
  }

  .progress-bar::-webkit-progress-value {
    background: linear-gradient(to right, #95d475, #67c23a);
    border-radius: 6px;
    transition: width 0.3s ease;
  }

  .progress-value {
    margin-left: 12px;
    color: #67c23a;
    font-weight: 500;
  }

  /* 响应式优化 */
  @media (max-width: 768px) {
    .task-content {
      flex-direction: column;
    }
    
    .task-status {
      margin: 16px 0 0 0;
    }
    
    .video-player {
      width: 100%;
    }
  }

  @media (max-width: 1200px) {
    .task {
      width: 95%;
    }
  }
</style>
